package com.awcall.iot.service.impl;

import com.awcall.iot.common.ResponseResult;
import com.awcall.iot.model.Role;
import com.awcall.iot.model.RoleAuthority;
import com.awcall.iot.mapper.RoleAuthorityMapper;
import com.awcall.iot.service.IRoleAuthorityService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 角色-权限 关联表 服务实现类
 * </p>
 *
 * @author wuhui
 * @since 2018-03-05
 */
@Service
public class RoleAuthorityServiceImpl extends ServiceImpl<RoleAuthorityMapper, RoleAuthority> implements IRoleAuthorityService {

    @Override
    public List<RoleAuthority> findByRoleId(Long id) {
        Wrapper<RoleAuthority> wrapper = new EntityWrapper<RoleAuthority>()
                .and(RoleAuthority.ROLE_ID + " = " + id);
        return selectList(wrapper);
    }

    @Override
    public ResponseResult updateAuthority(Role role) {
        if (null == role.getId()) {
            return new ResponseResult(1, "角色ID为空");
        }

        EntityWrapper<RoleAuthority> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq(RoleAuthority.ROLE_ID, role.getId());
        delete(entityWrapper);
        if (role.getRoleAuthorityList().isEmpty()) {
            return new ResponseResult();
        }

        role.getRoleAuthorityList()
                .forEach(roleAuthority -> roleAuthority.setRoleId(role.getId()));
        insertBatch(role.getRoleAuthorityList());
        return new ResponseResult();
    }

}
